package cn.edu.njust.heartbeat;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HeartBeatClientHandler extends ChannelInboundHandlerAdapter {

    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // 发送的消息不需要任何实际内容
                ctx.writeAndFlush(Unpooled.copiedBuffer(new byte[]{0}));
                log.info("发送心跳给服务器");
            }
        }, 5, 5, TimeUnit.SECONDS);
    }
}
